<script setup lang="ts">
import { ref ,onMounted} from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import request from "@/utils/request";
// 导入获取用户信息的接口函数
import { getUserInfoApi } from "@/api/user";// 根据实际路径替换

const currentUserUsername = ref('');

onMounted(() => {
  getUserInfoApi().then(res => {
    currentUserUsername.value = res.data.username;
    // 获取公司列表
    getCompanyList();
    // 获取列表，带上当前用户条件
    getList();
  }).catch(() => {
    ElMessage.error('获取当前用户信息失败，请重试');
  });
});


// 默认查询表单
const getDefaultSearchForm = () => ({
  pageNo: 1,
  pageSize: 10,
  statement: "",
  createBy: "",
  companyId: null,
});

// 类型定义
type StatementItem = {
  id: number; // 添加 ID 字段
  companyId: number;
  statement?: string;
  createBy: string;
  [key: string]: any; // 其他动态属性
};

type Company = {
  value: number;
  label: string;
};

// 状态管理
const searchForm = ref(getDefaultSearchForm());
const list = ref<StatementItem[]>([]);
const total = ref<number>(0);
const companyList = ref<Company[]>([]);
const selectedIds = ref<number[]>([]); // 批量删除的选中 ID 集合

// 获取列表
const getList = () => {
  searchForm.value.createBy = currentUserUsername.value; // 添加当前登录用户名作为查询条件
  request.post('/api/v1/statement/searchStatement', searchForm.value).then(res => {
    const { data } = res;
    list.value = data.list.map(item => {
      const company = companyList.value.find(c => c.value === item.companyId);
      item.companyName = company ? company.label : "未知公司";
      return item;
    });
    total.value = data.total;
  });
};

// 获取公司列表
const getCompanyList = () => {
  request.get('/api/v1/statement/company').then(res => {
    companyList.value = res.data;
  });
};

// 初始化数据
getCompanyList();
getList();

// 重置查询
const resetSearch = () => {
  searchForm.value = getDefaultSearchForm();
  searchForm.value.createBy = currentUserUsername.value; // 添加当前登录用户名
  getList();
};

// 分页变化
const currentChange = (pageNo: any) => {
  searchForm.value.pageNo = pageNo;
  getList();
};

// 监听表格选中变化
const handleSelectionChange = (selection: StatementItem[]) => {
  selectedIds.value = selection.map(item => item.id);
};

// 批量删除
const deleteSelected = () => {
  if (selectedIds.value.length === 0) {
    ElMessage.warning("请选择要删除的客服记录");
    return;
  }

  ElMessageBox.confirm(`确定要删除选中的 ${selectedIds.value.length} 条记录吗？`, '提示', {
    confirmButtonText: '删除',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    request.post('/api/v1/statement/batchStatementDelete', selectedIds.value).then(() => {
      ElMessage.success('批量删除成功');
      getList(); // 刷新列表
      selectedIds.value = []; // 清空选中项
    }).catch(() => {
      ElMessage.error('批量删除失败，请重试');
    });
  }).catch(() => {
    ElMessage.info('已取消删除');
  });
};

// 表单逻辑：新增和编辑共用
const addForm = ref({
  id: null,          // 常用语id
  companyId: "",    // 公司ID
  statement: "",          //常用语句内容
  createBy: "",   // 创建人
});
const dialogVisible = ref(false);

// 打开新增对话框
const openAddDialog = () => {
  addForm.value = { id: null, companyId: "", statement: "", createBy: currentUserUsername.value };
  dialogVisible.value = true;
};

// 打开编辑对话框
const editService = (row: any) => {
  // 使用解构赋值去除 companyName 字段，只保留原始定义的字段
  const { companyName,...rest } = row;
  addForm.value = rest;
  dialogVisible.value = true;
};

// 提交表单
const handleSubmit = () => {
  if (addForm.value.id) {
    // 编辑
    request.put('/api/v1/statement/updateStatement', addForm.value).then(() => {
      dialogVisible.value = false;
      getList();
    });
  } else {
    // 新增
    request.post('/api/v1/statement/addStatement', addForm.value).then(() => {
      dialogVisible.value = false;
      getList();
    });
  }
};

// 删除
const deleteStatement = (id: number) => {
  ElMessageBox.confirm('确定要删除这条记录吗？', '提示', {
    confirmButtonText: '删除',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    request.delete(`/api/v1/statement/deleteStatement/${id}`).then(() => {
      ElMessage.success('删除成功');
      getList();
    }).catch(() => {
      ElMessage.error('删除失败，请重试');
    });
  }).catch(() => {
    ElMessage.info('已取消删除');
  });
};

// 查看详情
const viewService = (row: any) => {
  ElMessageBox.alert(`
    <div>
      <p><strong>常用语内容：</strong>${row.statement}</p>
      <p><strong>所在公司：</strong>${row.companyName || "未知公司"}</p>
      <p><strong>创建人：</strong>${row.createBy}</p>
    </div>
  `, '常用语详情', {
    dangerouslyUseHTMLString: true,
    confirmButtonText: '确定',
  });
};

</script>

<template>
  <div style="padding: 16px;">
    <el-card :body-style="{ paddingBottom: '0' }">
      <el-form inline>
        <el-form-item label="常用语句内容">
          <el-input v-model="searchForm.statement" placeholder="请输入常用语句内容" />
        </el-form-item>
<!--        <el-form-item label="创建人">
          <el-input v-model="searchForm.createBy" placeholder="请输入创建人" />
        </el-form-item>-->
        <el-form-item label="公司名称">
          <el-select v-model="searchForm.companyId" placeholder="请选择公司" style="width: 200px;">
            <el-option v-for="item in companyList" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="getList" type="primary">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card style="margin-top: 16px;">
      <template #header>
        <el-button @click="deleteSelected" type="danger" style="margin-right: 8px;">批量删除</el-button>
        <el-button @click="openAddDialog" type="primary">新增</el-button>
      </template>
      <el-table
          :data="list"
          @selection-change="handleSelectionChange"
          style="text-align: left;"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="statement" label="常用语句内容" width="300" />
        <el-table-column prop="companyName" label="所在公司" width="300" />
<!--        <el-table-column prop="createBy" label="创建人" width="200" />-->
        <el-table-column label="操作" width="300" fixed="right" align="center">
          <template #default="{ row }">
            <el-button type="success" @click="viewService(row)">查看</el-button>
            <el-button type="primary" @click="editService(row)">编辑</el-button>
            <el-button type="danger"  @click="deleteStatement(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination @current-change="currentChange" :total="total" layout="prev, pager, next" />
    </el-card>
    <el-dialog v-model="dialogVisible" title="常用语管理" top="0">
      <el-form label-position="top">
        <el-form-item label="常用语内容">
          <el-input v-model="addForm.statement" placeholder="请输入常用语内容"/>
        </el-form-item>
        <el-form-item label="公司名称">
          <el-select v-model="addForm.companyId" placeholder="请选择公司">
            <el-option v-for="item in companyList" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>

  </div>
</template>